jQuery.fn.extend({  
    fillForm:function(options){  
        var settings = jQuery.extend({  
            prefix:'' 
            ,data:{} 
        },options);  
    this.each(function(){  
        var that =jQuery(this);  
        if(jQuery.inArray(that.attr('tagName').toLowerCase(),['input','select','radio','textarea'])>-1){  
            that.val(settings.data[that.attr('name')]);  
        }else{  
            for(var item in settings.data){  
                try{  
                    that.find('[name=\''+settings.prefix+item+'\']').val(settings.data[item]);  
                }catch(e){  
                    if(window.console){  
                        console.error('Î´ÄÜ»ñÈ¡ÔªËØ:'+settings.prefix+item);  
                    }  
                }  
            }  
        }  
    });  
    }  
    ,getForm:function(options){   
        var ret =[];  
        var forms = this;  
        forms.each(function(){  
            var that =jQuery(this);  
            var o ={};  
            that.find('input,select,radio,textarea').each(function(){
                var el = jQuery(this); 
				var type = el.attr('type');
				if(el.is('input') && (type=='button' || type=='reset' || type=='submit'))
					return true;
                var fieldName = el.attr('name');  
                o[fieldName] = el.val();  
            });  
            ret.push(o);  
        });  
        if(ret.length === 1)return ret[0];  
        return ret;  
    }  
}); 

function startTime(){
	var today=new Date() //新建一个日期对象
	var y=today.getFullYear();
	var mo=today.getMonth();
	var d=today.getDate();
	var weekday=today.getDay();
	var h=today.getHours()//获得时
	var m=today.getMinutes()//获得分
	var s=today.getSeconds()//获得秒
	// var ss=today.getMilliseconds().toString().substr(0,2)//毫秒.取出来是三位,这里只显示两位
	// add a zero in front of numbers<10
	m=checkTime(m)
	s=checkTime(s)
	mo=checkTime(mo)
	d=checkTime(d);
	document.getElementById('current_time').innerHTML=y+'年'+mo+'月'+d+'日 '+h+":"+m+":"+s;
	t=setTimeout('startTime()',1000)//刷新时间
}

function checkTime(i){
if (i<10)
 	{i="0" + i}
 	return i
}
function getDaysBetween(date1,date2){
    var arr1=date1.split('-');
    var arr2=date2.split('-');
    var d1=new Date(arr1[0],arr1[1],arr1[2]);
    var d2=new Date(arr2[0],arr2[1],arr2[2]);
    return ((d2.getTime()-d1.getTime())/(1000*3600*24));
}
function teacherTypeChanged(){
	var courseType=document.getElementById("course_type_select").selectedIndex;
	var select = document.getElementById("teacher_type_select");
	var index = select.selectedIndex;
	var type = select.options[index].value;
	var cred = document.getElementById("cred_field");
	var qut = document.getElementById("quantity_select");
	var allQut = document.getElementById("all_quantity");
	if(courseType == 1){
		switch(index){
		case 0:
			qut.length=0;
			qut.options.add(new Option(allQut.options[4].text,allQut.options[4].value));
			cred.innerHTML="工资号：";
			break;
		case 1:
			qut.length=0;
			qut.options.add(new Option(allQut.options[4].text,allQut.options[4].value));
			cred.innerHTML="身份证号：";
			break;
		case 2:
			qut.length=0;
			qut.options.add(new Option(allQut.options[5].text,allQut.options[5].value));
			cred.innerHTML="护照号：";
			break;
		}
	}else{
		switch(index){
		case 0:
			qut.length=0;
			qut.options.add(new Option(allQut.options[0].text,allQut.options[0].value));
			qut.options.add(new Option(allQut.options[1].text,allQut.options[1].value));
			cred.innerHTML="工资号：";
			break;
		case 1:
			qut.length=0;
			qut.options.add(new Option(allQut.options[0].text,allQut.options[0].value));
			qut.options.add(new Option(allQut.options[1].text,allQut.options[1].value));
			cred.innerHTML="身份证号：";
			break;
		case 2:
			qut.length=0;
			qut.options.add(new Option(allQut.options[2].text,allQut.options[2].value));
			qut.options.add(new Option(allQut.options[3].text,allQut.options[3].value));
			cred.innerHTML="护照号：";
			break;
		}
	}
	quantityChanged();
}

function quantityChanged(){
	var qut = document.getElementById("quantity_select");
	var index = qut.selectedIndex;
	var str = qut.options[index].text;
	var splits = str.split('/');
	var unit = document.getElementById("salary_unit");
	unit.innerHTML=splits[0];
}
function checkSalaryStandard(number, t, local){
	var type = parseInt( t );
	var num = parseInt(number);
	switch(type){
	case 0:
		if((num<0||num>1000) && !local)
			return false;
		if((num<0||num>500 )&& local)
			return false
		break;
	case 1:
		if(num<0)
			return false;
		break;
	case 2:
		if(num<0||num>200)
			return false;
		break;
	case 3:
		if(num<0||num>10000)
			return false;
		break;
	case 4:
		if((num<0||num>3000)&&local)
			return false;
		break;
	case 5:
		if(num<0)
			return false;
		break;
	}
	return true;
}

function activityTypeChanged(){
	var index=document.getElementById("activity_type_select").selectedIndex;
	var select = document.getElementById("activity_subtype_select");
	select.length=0;
	var s_index=index+1;
	var clone = document.getElementById("extra_select_"+s_index);
	for(var i=0;i<clone.length;i++){
		select.options.add(new Option(clone.options[i].text,clone.options[i].value) );
	}
}
$(document).ready(function(){
	var data_cache;
	startTime();
	$.showTips = function(title,content,time){
		if(time=='undefined')
			time=1000;
		$("#n_title").html(title);
		$("#n_content").html(content);
		$("#notification").stop(true,true).hide();
		$("#notification").stop(true,true).show();
		if(time!=0){
			setTimeout(function(){
				$("#notification").stop(true,true).fadeOut(2000);
			},time);	
		}else{
			$("body").one("click",function(){
				$("#notification").stop(true,true).fadeOut(1000);
			});
		}
	}
	$.runAjax = function(ajaxurl){
		$.ajax({url:ajaxurl,data:{"method":"ajax"},beforeSend:function(){
			$("#preloading").show();
		},success:function(result){
			//截取符合json格式的头数据
			var matches = result.match(/^{.+}/i);
			var json;
			var htmlLoad=true;
			var content="";
			if(matches && result.indexOf(matches[0])==0){
				json = $.parseJSON(matches[0]);
				content = result.substring(matches[0].length+1);
				if(json.type=="login"){
					location.href="../user/login";
				}else if(json.type=="forbid"){
					htmlLoad=false;
				}
				//生成提示框
				$.showTips(json.title,json.content,2000);
			}else{
				content=result;
			}
			if(htmlLoad){
				$('#content').html(content);
			}
		},complete:function(result){
			$("#preloading").hide();
		}});
	};
	$('.hasdatepicker').live('mouseenter', function() {
		$(this).datepicker({
               dateFormat: 'yy-mm-dd',//日期格式  
               changeMonth:true,
               changeYear:true,
        });
		 $("#ui-datepicker-div").css('font-size','0.8em');
	});
	
	$('.fold_menu div').click(function(){
		var name="";
		name = $(this).attr('name');
		if(typeof(name)=='undefined'){
			return;
		}
		name = name.toLowerCase();
		var splits,controller,action;
		splits = name.split('_');
		action = splits[1];
		controller = splits[0];
		var ajaxurl = '../'+controller+'/'+action;
		$.runAjax(ajaxurl);
	});
	
	$('.form_post').live("click",function(){
		var form=$(this).parent();
		while(! form.is("form")){
			form = form.parent();
			if(form.is("body"))
				return;
		}
		var valid = true;
		form.find("input[type='text']").each(function(){
			var input = $(this);
			if(input.val()==""&&!input.hasClass("not-required")){
				var attr = input.parent().find(".field_name").html();
				$.showTips(attr,"该属性不能为空！",0);
				valid=false;
				return false;
			}
		});
		if(!valid)
			return;
		var postData=form.getForm();
		var ajaxurl =form.attr('action');
		$.ajax({type:"post",url:ajaxurl,data:postData,success:function(result){
			//截取符合json格式的头数据
			var matches = result.match(/^{.+}/i);
			var json;
			var htmlLoad=true;
			var content="";
			if(matches && result.indexOf(matches[0])==0){
				json = $.parseJSON(matches[0]);
				content = result.substring(matches[0].length+1);
				if(json.type=="login"){
					location.href="../user/login";
				}else if(json.type=="forbid"){
					htmlLoad=false;
				}
				//生成提示框
				$.showTips(json.title,json.content,2000);
			}else{
				content=result;
			}
			if(htmlLoad){
				$('#content').html(content);
			}
			//$('#content').html(result);
		}});
	});
	$('.ajaxbtn').live("click",function(){
		if($(this).html()=="删除"){
			if(!confirm("确定删除？"))
				return;
		}
		var name="";
		name = $(this).attr('name');
		if(typeof(name)=='undefined'){
			return;
		}
		name = name.toLowerCase();
		var splits,controller,action;
		splits = name.split('_');
		var url="";
		var tmp;
		for(tmp in splits)
			url+="/"+splits[tmp];
		var ajaxurl = '..'+url;
		$.runAjax(ajaxurl);
	});
	$('.menu_title_wrap').click(function(){
		var n =$('.menu_title_wrap').index($(this));
		$('.fold_menu_wrap:eq('+n+')').slideToggle('slow');
	});
	$(".hasdatepicker").live("click",function(){
		date_cache = $(this).val();
	});
	$(".hasdatepicker").live("change",function(){
		var begin = $("#begin_date").attr("value");
		var end =$("#end_date").attr("value");
		var days = getDaysBetween(begin,end);
		var weeks = Math.ceil(days/7);
		if(weeks<0){
			alert("日期输入有误！");
			$(this).val(date_cache);
		}else{
			$("#weeks_input").val(weeks);
			var weeks = $("#weeks_input").val();
			var unit = $("#unit_input").val();
			var units = weeks*unit;
			$("#units_input").val(units);
		}
	});
	$("#unit_input").live("blur",function(){
		var weeks = $("#weeks_input").val();
		var unit = $(this).val();
		var units = weeks*unit;
		$("#units_input").val(units);
	});
	$("#salary_standard_input").live("blur",function(){
		var num=$(this).val();
		var type = $("#quantity_select").val();
		var local=false;//本校教师
		if($("#teacher_type_select").val()==1)
			local = true;
		if(!checkSalaryStandard(num,type,local)){
			$.showTips("提示","课酬标准不符合规定！",2000);
			$(this).val(0);
		}
	});
	$("#list .row").live("click",function(){
		var n = $("#list div.row").index($(this));
		$("#list div.operator:not(':eq("+n+")'):visible").hide("fast");
		$("#list div.operator:eq("+n+")").slideToggle("slow");
	});
	//click default button when first load
	$(".default_click:eq(0)").trigger("click");
	
});


